package com.gy.studyonlineapp.callback;

import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

import com.gy.studyonlineapp.activity.LoginActivity;
import com.gy.studyonlineapp.constants.LearnCloudClass;

import java.util.List;

import cn.leancloud.AVObject;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class RegAVQueryObserver implements Observer<List<AVObject>> {

    private Context context;

    private String username;

    private String password;

    public RegAVQueryObserver(){}


    public RegAVQueryObserver(Context context,String username,String password) {
        this.context = context;
        this.username = username;
        this.password = password;
    }

    @Override
    public void onSubscribe(Disposable d) {

    }

    @Override
    public void onNext(List<AVObject> StudyOnlineUser) {
        if (StudyOnlineUser != null && StudyOnlineUser.size() == 1){
            Toast.makeText(context,"该用户名已被注册，请重新输入用户名",Toast.LENGTH_LONG).show();
            return;
        }else {//注册
            AVObject user = new AVObject(LearnCloudClass.STUDYONLINEUSER);
            user.put("username",username);
            user.put("password",password);
            user.saveInBackground().subscribe(new Observer<AVObject>() {
                @Override
                public void onSubscribe(Disposable d) {

                }

                @Override
                public void onNext(AVObject user) {
                    //注册成功并保存到数据库，跳转至登录页面
                    Toast.makeText(context,"注册成功!",Toast.LENGTH_LONG).show();
                    context.startActivity(new Intent(context, LoginActivity.class));
                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onComplete() {

                }
            });
        }
    }

    @Override
    public void onError(Throwable e) {

    }

    @Override
    public void onComplete() {

    }
}
